package com.qf.service.impl;

import com.qf.dao.TeacherRepository;
import com.qf.pojo.RedisKey;
import com.qf.pojo.respVo.BaseResp;
import com.qf.pojo.vo.QfTeach;
import com.qf.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    TeacherRepository teacherRepository;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public BaseResp findAll() {

        //判断redis是否有该key
        Boolean aBoolean = redisTemplate.hasKey(RedisKey.TEACHER);
        List range=null;
        if (aBoolean){
             range = redisTemplate.opsForList().range(RedisKey.TEACHER, 0, -1);
        }else {
            range  = teacherRepository.findAll();
            //判断 数据库是否有值，防止缓存穿透
            if (range==null||range.size()==0){
                redisTemplate.opsForList().leftPush(RedisKey.TEACHER,"null");
                redisTemplate.expire(RedisKey.TEACHER,1, TimeUnit.MINUTES);
            }else{
                //放到redis中
                redisTemplate.opsForList().leftPushAll(RedisKey.TEACHER,range);

            }
        }
        return new BaseResp(1,"查询成功！",range,null);
    }
}
